import md5 from "js-md5";
import http from "@/api/http.js";

const availableNums = "0123456789";
const availableChars = "abcdefghijklmnopqrstuvwxyz";

export function createID() {
  let charCount = 8;
  let numCount = 16;

  let str = "#";
  for (let i = 0; i < charCount; i++) {
    let idx = parseInt(Math.random() * availableChars.length);
    str += availableChars[idx];
  }

  for (let i = 0; i < numCount; i++) {
    let idx = parseInt(Math.random() * availableNums.length);
    str += availableNums[idx];
  }
  return str;
}

export function uuid(len, radix) {
  var chars =
    "0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz".split("");
  var uuid = [],
    i;
  radix = radix || chars.length;

  if (len) {
    // Compact form
    for (i = 0; i < len; i++) uuid[i] = chars[0 | (Math.random() * radix)];
  } else {
    // rfc4122, version 4 form
    var r;

    // rfc4122 requires these characters
    uuid[8] = uuid[13] = uuid[18] = uuid[23] = "-";
    uuid[14] = "4";

    // Fill in random data.  At i==19 set the high bits of clock sequence as
    // per rfc4122, sec. 4.1.5
    for (i = 0; i < 36; i++) {
      if (!uuid[i]) {
        r = 0 | (Math.random() * 16);
        uuid[i] = chars[i == 19 ? (r & 0x3) | 0x8 : r];
      }
    }
  }

  return uuid.join("");
}

export function parseJwt(token) {
  if (!token) return;
  const payload = token.split(".")[1];
  return atob(payload);
}

/**
 * 
 * @returns 返回格式为 2024-6-14 13:27:26
 */
export function getNow() {
  const date = new Date();
  return date.toLocaleString().replaceAll("/", "-");
}

/**
 * 获取存储在session中的用户角色ID
 * @returns 
 */
export function getRole() {
  let info = sessionStorage.getItem("userInfo");
  let userInfo = JSON.parse(info);
  return userInfo.role.roleid;
}

/**
 * 获取本机IP地址
 * @returns 
 */
export function getIPAddress() {
  return new Promise((resolve, reject) => {
    fetch("https://api.ipify.org/?format=json")
      .then((response) => response.json())
      .then((data) => {
        const ipAddress = data.ip;
        resolve(ipAddress);
      })
      .catch((error) => {
        reject(error);
      });
  });
}

/**
 * 处理文件上传逻辑
 * @param {*} param 
 * @param {*} bizId 
 * @returns 
 */
export function handleUpload(param, bizId) {
  let formData = new FormData();
  formData.append("files", param.file);
  formData.append("bizId", bizId);

  return new Promise((resolve, reject) => {
    http({
      url: "/file/api/upload",
      method: "post",
      headers: {
        "Content-Type": "multipart/form-data",
      },
      data: formData,
    })
      .then((res) => {
        resolve(res);
      })
      .catch((err) => {
        reject(err);
      });
  });
}

/**
 * 格式化日期，将日期转换为如下格式：
 * 2024-06-14 13:30
 * @param {*} date 
 * @returns 
 */
export function dateFormat(date) {
  let year = date.getFullYear();
  let month = date.getMonth() + 1;
  month = month >= 10 ? month : "0" + month;
  let day = date.getDate();
  day = day >= 10 ? day : "0" + day;
  let hour = date.getHours();
  hour = hour >= 10 ? hour : "0" + hour;
  let minutes = date.getMinutes();
  minutes = minutes >= 10 ? minutes : "0" + minutes;
  let seconds = date.getSeconds();
  seconds = seconds >= 10 ? seconds : "0" + seconds;
  return (
    year + "-" + month + "-" + day + " " + hour + ":" + minutes + ":" + seconds
  );
}

/**
 * 将短时间戳转换为 时分秒形式
 * 例如：
 *      01:30:29
 * @param {*} num 
 * @returns 
 */
export function durationFormat(num) {
  let hour = Math.floor((num / 3600) % 24);
  hour = hour < 10 ? "0" + hour : hour;
  let minutes = Math.floor((num / 60) % 60);
  minutes = minutes < 10 ? "0" + minutes : minutes;
  let seconds = Math.floor(num % 60);
  seconds = seconds < 10 ? "0" + seconds : seconds;
  return `${hour}:${minutes}:${seconds}`;
}

export function isLiveOwner(uid) {
  let userInfo = JSON.parse(sessionStorage.getItem("userInfo"));
  if (userInfo && uid == userInfo.userid) {
    return true;
  }
  return false;
}

// time1 当前时间,time2 结束时间
/**
 * 这里比较的是时间戳
 * @param {*} time1 new Date().getTime() ==> 1718342846526
 * @param {*} time2 Date.parse("2024-05-16 12:30") ==> 1715833800000
 * @returns 
 */
export function isNotEnd(time1, time2) {
  return time1 < Date.parse(time2);
}

// 深拷贝
export function deepCopy(obj) {
  if (obj === null || typeof obj !== "object") {
    return obj;
  }

  let copy;
  if (Array.isArray(obj)) {
    copy = [];
    for (let i = 0; i < obj.length; i++) {
      copy[i] = deepCopy(obj[i]);
    }
  } else {
    copy = {};
    for (let key in obj) {
      if (obj.hasOwnProperty(key)) {
        copy[key] = deepCopy(obj[key]);
      }
    }
  }

  return copy;
}
